package com.ruoyi.web.controller;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.entity.IssuerUnit;
import com.ruoyi.common.utils.http.HttpResult;
import com.ruoyi.common.utils.jm.CertStruct;
import com.ruoyi.common.utils.jm.RSACrypto;
import com.ruoyi.system.service.IIssuerUnitService;
import com.ruoyi.web.config.AliyunMQConfig;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.AuthenticateToken;
import com.ruoyi.common.core.domain.entity.AuthenticateUser;
import com.ruoyi.common.utils.Base64Utils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.system.service.IAuthenticateTokenService;
import com.ruoyi.system.service.IAuthenticateUserService;
import com.ruoyi.web.bean.PDFPage;
import com.ruoyi.web.bean.PdfLocation;
import com.ruoyi.web.config.ProducerUtil;
import com.ruoyi.web.dto.SealDto;
import com.ruoyi.web.service.CQYCSignService;
import com.ruoyi.web.service.FileService;
import com.ruoyi.web.util.ImgBean;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.aliyun.openservices.ons.api.SendResult;
import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import java.awt.*;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.util.List;

import static com.ruoyi.common.utils.Base64Utils.ESSGetBase64Decode;
import static com.ruoyi.common.utils.Base64Utils.ESSGetBase64Encode;
import static com.ruoyi.common.utils.StringUtils.isNull;
import static com.ruoyi.common.utils.file.FileUtils.byte2Input;
import static com.ruoyi.common.utils.http.MyHttpHelper.executePost;
import static com.ruoyi.web.util.TestSignImg.createTextImage;
import static com.ruoyi.web.util.pdf.PdfUtils.convertCoordinate;

/**
 * 第三方身份认证签章（浙江烟草）
 */
@Slf4j
@Controller
@RequestMapping(value="/authenticate")
public class AuthenticateController {
    @Resource
    public IAuthenticateTokenService authenticateTokenService;
    @Resource
    public IAuthenticateUserService authenticateUserService;
    @Resource
    public FileService fileService;
    @Autowired
    private IIssuerUnitService iIssuerUnitService;
    @Autowired
    private CQYCSignService signService;
    //0成功 ，1失败
    private static String authMsg_default = "2";
    private static String authMsg_success = "0";
    private static String authMsg_error = "1";

    private static String sign_default = "2";
    private static String sign_success = "0";
    private static String sign_error = "1";
    @Autowired
    @Qualifier("smsTopicProperties")
    private AliyunMQConfig.TopicProperties smsTopicProperties;
    @Autowired
    private ProducerUtil producerUtil;


    @Value("${PDFConvert.faceServerUrl}")
    public String faceServerUrl;
    @Value("${PDFConvert.faceSysId}")
    public String faceSysId;
    @Value("${PDFConvert.partner}")
    public String partner;
    /**
     * 获取签章token
     * 参数示例
     *
     * @param data
     * @return
     */
    @RequestMapping(value="/getSignToken")
    @ResponseBody
    public AjaxResult getSignToken(@RequestBody JSONObject data) {
//        //检查参数
        String name;
        String identityCard;
        String documentCode;
        String documentName;
        JSONArray seals = new JSONArray();
        if (data.containsKey("name") && data.containsKey("identityCard")&& data.containsKey("documentCode")
                && data.containsKey("documentCode")) {
            name = data.getString("name");
            identityCard = data.getString("identityCard");
            documentCode = data.getString("documentCode");
            documentName = data.getString("documentName");
            seals =data.getJSONArray("seals");
        } else {
            return AjaxResult.error("参数类型不全");
        }
        //生产tokenId ,保存参数
        AuthenticateToken authenticateToken = new AuthenticateToken();
        authenticateToken.setDocumentId(documentCode);
        authenticateToken.setSeals(seals.toJSONString());
        authenticateToken.setIdCard(identityCard);
        authenticateToken.setName(name);
        authenticateToken.setDocumentName(documentName);
        authenticateToken.setUnitName("浙江省烟草专卖局");
        authenticateToken.setAuthStatus(authMsg_default);
        authenticateToken.setSignStatus(sign_default);
        int add_result = authenticateTokenService.insertAuthenticateToken(authenticateToken);
        //如果身份信息不为空的话，新增人员
        if(!"".equals(identityCard)&&!"".equals(name)){
            //新增人员之前检查是否存在
            AuthenticateUser authenticateUser = authenticateUserService.selectAuthenticateUserByUserId(identityCard);
            if (authenticateUser!=null){
                authenticateUserService.deleteAuthenticateUserByUserId(identityCard);
            }
            authenticateUser = new AuthenticateUser();
            authenticateUser.setUserId(identityCard);
            authenticateUser.setName(name);
            authenticateUserService.insertAuthenticateUser(authenticateUser);
        }

        if (add_result==1){
            return AjaxResult.success("获取成功",authenticateToken.getTokenId());
        }
        return AjaxResult.error("获取失败");
    }
    /**
     * 根据token更新人员数据
     *
     */
    @RequestMapping(value="/addUser")
    @ResponseBody
    public AjaxResult addUser(@RequestBody JSONObject data) {
        //检查参数
        String token;
        String name;
        String identityCard;
        if (data.containsKey("name") && data.containsKey("identityCard") && data.containsKey("token")) {
            token = data.getString("token");
            name = data.getString("name");
            identityCard = data.getString("identityCard");
        } else {
            return AjaxResult.error("参数类型不全");
        }
        AuthenticateToken authenticateToken = authenticateTokenService.selectAuthenticateTokenByTokenId(token);
        if (authenticateToken == null&&sign_success.equals(authenticateToken.getSignStatus())){
            return AjaxResult.error("token已失效");
        }
        authenticateToken.setIdCard(identityCard);
        authenticateToken.setName(name);
        int a = authenticateTokenService.updateAuthenticateToken(authenticateToken);
        //新增人员之前检查是否存在
        AuthenticateUser authenticateUser = authenticateUserService.selectAuthenticateUserByUserId(identityCard);
        if (authenticateUser!=null){
            authenticateUserService.deleteAuthenticateUserByUserId(identityCard);
        }
        authenticateUser = new AuthenticateUser();
        authenticateUser.setUserId(identityCard);
        authenticateUser.setName(name);
        authenticateUserService.insertAuthenticateUser(authenticateUser);

        return AjaxResult.success("新增成功");
    }
    /**
     * 根据token获取本次签章的第三方人员信息
     */
    @RequestMapping(value="/getUserByToken")
    @ResponseBody
    public AjaxResult getUserByToken(@RequestBody JSONObject data) {
        String token;
        if (data.containsKey("token")) {
            token = data.getString("token");
        } else {
            return AjaxResult.error("参数类型不全");
        }
        AuthenticateToken authenticateToken = authenticateTokenService.selectAuthenticateTokenByTokenId(token);
        if (authenticateToken == null&&sign_success.equals(authenticateToken.getSignStatus())){
            return AjaxResult.error("token已失效");
        }
        return AjaxResult.success("获取成功",authenticateToken);
    }
    /**
     * 根据token更新人员数据
     */
    @RequestMapping(value="/updateUser")
    @ResponseBody
    public AjaxResult updateUser(@RequestBody JSONObject data) {
        String token;
        String signImg;
        String idCardImg;
        String faceImg;
        if (data.containsKey("token")) {
            token = data.getString("token");
        } else {
            return AjaxResult.error("参数类型不全");
        }
        AuthenticateToken authenticateToken = authenticateTokenService.selectAuthenticateTokenByTokenId(token);
        if (authenticateToken == null&&sign_success.equals(authenticateToken.getSignStatus())){
            return AjaxResult.error("token已失效");
        }
        String id = authenticateToken.getIdCard();
        AuthenticateUser authenticateUser =authenticateUserService.selectAuthenticateUserByUserId(id);
        if (data.containsKey("signImg")) {

//            byte[] img = null;
//            BufferedImage src = null;
//            try {
//                src = ImageIO.read(FileUtils.byte2Input(img));
//                //顺时针旋转90度
//                BufferedImage des1 = RotateImage.Rotate(src, 90);
//                ImageIO.write(des1, "jpg", new File("e:/90.jpg"));
//                //顺时针旋转180度
//                BufferedImage des2 = RotateImage.Rotate(src, 180);
//                ImageIO.write(des2, "jpg", new File("c:/180.jpg"));
//                //顺时针旋转270度
//                BufferedImage des3 = RotateImage.Rotate(src, 270);
//                ImageIO.write(des3, "jpg", new File("c:/270.jpg"));
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
            signImg = data.getString("signImg");
            authenticateUser.setSignImg(signImg);
        } else  if(data.containsKey("idCardImg"))  {
            idCardImg = data.getString("idCardImg");
            authenticateUser.setIdCardImg(idCardImg);
        } else if(data.containsKey("faceImg")) {
            faceImg = data.getString("faceImg");
            authenticateUser.setFaceImg(faceImg);
        }
        int update_result = authenticateUserService.updateAuthenticateUser(authenticateUser);
        if (update_result==1){
            return AjaxResult.success("修改成功",authenticateToken.getTokenId());
        }
        return AjaxResult.error("修改失败");
    }

    /**
     * 生成证书
     * @param data
     * @return
     */
    @RequestMapping(value="/createCert")
    @ResponseBody
    public AjaxResult createCert(@RequestBody JSONObject data) {
        String token;
        if (data.containsKey("token")) {
            token = data.getString("token");
        } else {
            return AjaxResult.error("参数类型不全");
        }
        AuthenticateToken authenticateToken = authenticateTokenService.selectAuthenticateTokenByTokenId(token);
        if (authenticateToken == null&&sign_success.equals(authenticateToken.getSignStatus())){
            return AjaxResult.error("token已失效");
        }
        String id = authenticateToken.getIdCard();
        AuthenticateUser authenticateUser =authenticateUserService.selectAuthenticateUserByUserId(id);
        IssuerUnit issuerUnit = new IssuerUnit();
        issuerUnit.setAlgorithm("SHA1withRSA");
        List<IssuerUnit> issuerUnits = iIssuerUnitService.selectIssuerUnitList(issuerUnit);

        issuerUnit  = issuerUnits.get(0);
        //生成证书
        CertStruct cert = null;
        try {
            cert = RSACrypto.CreateUserRSAPfx("浙江省","","浙江省烟草专卖局",
                    "",authenticateUser.getName(),ESSGetBase64Decode(issuerUnit.getIssuerUnitRoot()),
                    ESSGetBase64Decode(issuerUnit.getIssuerUnitPfx()),issuerUnit.getPfxPwd());
        } catch (GeneralSecurityException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        authenticateUser.setCert(ESSGetBase64Encode(cert.bCert));
        authenticateUser.setPfx(ESSGetBase64Encode(cert.bPfx));
        authenticateUser.setPwd(cert.sPin);
        int update_result = authenticateUserService.updateAuthenticateUser(authenticateUser);
        if (update_result==1){
            return AjaxResult.success("创建成功",authenticateToken.getTokenId());
        }
        return AjaxResult.error("创建失败");
    }
    /**
     * 根据token 获取文档页面
     * @param data 数据
     * @throws IOException 异常
     *
     * 参数
     * {"token":"xxxxx","pageNum":"x"}
     *
     * 返回结果
     * {"pageImge":"图片base64数据","pageWidth":"x","pageHight":"x,"pageNumTotal":"x"}
     */
    @RequestMapping(value="/getDocumentPage")
    @ResponseBody
    public String getDocumentPage(@RequestBody JSONObject data){
        JSONObject result = new JSONObject();
        String token;
        int pageNum;
        if (data.containsKey("token")&&data.containsKey("pageNum")){
            token = data.getString("token");
            pageNum = data.getInteger("pageNum");
            //根绝token获取文档ID取得PDF文件
            AuthenticateToken authenticateToken = authenticateTokenService.selectAuthenticateTokenByTokenId(token);
            if (!isNull(authenticateToken)){
                String documentCode = authenticateToken.getDocumentId();
                byte[] pdfByte = fileService.downloadDocument(documentCode,"pdf");
                PDFPage pdfPage= fileService.getPDFPage(pdfByte,pageNum,96);
                if (isNull(pdfPage)){
                    result.put("code","w0004");
                    result.put("msg","文档页数错误");
                    return result.toJSONString();
                }
                result.put("code","w0000");
                result.put("msg","获取成功");
                JSONObject jsonObject = new JSONObject();
//                jsonObject.put("pageImge",pdfPage.getImageBase64());
                jsonObject.put("pageWidth",pdfPage.getWidth());
                jsonObject.put("pageHight",pdfPage.getHeight());
                jsonObject.put("pageNumTotal",pdfPage.getTolNum());
                result.put("data",jsonObject);
                return result.toJSONString();
            }else{
                result.put("code","w0003");
                result.put("msg","文档为空");
                return result.toJSONString();
            }
        }else{
            //参数格式错误
            result.put("code","w0002");
            result.put("msg","未找到符合要求的数据");
            return result.toJSONString();
        }
    }

    @RequestMapping(value="/getDocumentPageImg")
    @ResponseBody
    public void getDocumentPageImg(String token, int pageNum, HttpServletResponse response){
        //根绝token获取文档ID取得PDF文件
        AuthenticateToken authenticateToken = authenticateTokenService.selectAuthenticateTokenByTokenId(token);
        if (!isNull(authenticateToken)) {
            String documentCode = authenticateToken.getDocumentId();
            byte[] pdfByte = fileService.downloadDocument(documentCode, "pdf");
            PDFPage pdfPage = fileService.getPDFPageImg(pdfByte, pageNum, 96);
            try {
                byte[] bytes = ESSGetBase64Decode(pdfPage.getImageBase64());
                //设置MIME类型
                response.setContentType("image/gif");
                //设置头信息,设置文件下载时的默认文件名，同时解决中文名乱码问题
                response.addHeader("Content-disposition", "attachment;filename=" + token+".gif");
                //将文件流输出
                ServletOutputStream outputStream = response.getOutputStream();
                InputStream inputStream = FileUtils.byte2Input(bytes);
                int ch;
                while ((ch = inputStream.read()) != -1) {
                    outputStream.write(ch);
                }
                outputStream.close();
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     */
    @RequestMapping(value="/getAuthUrl")
    @ResponseBody
    public AjaxResult getAuthUrl(@RequestBody JSONObject data) {
        String token;
        if (data.containsKey("token")) {
            token = data.getString("token");
        } else {
            return AjaxResult.error("参数类型不全");
        }
        AuthenticateToken authenticateToken = authenticateTokenService.selectAuthenticateTokenByTokenId(token);
        if (authenticateToken == null&&sign_success.equals(authenticateToken.getSignStatus())){
            return AjaxResult.error("token已失效");
        }
        if (isNull(authenticateToken.getIdCard())){
            return AjaxResult.error("token信息缺失");
        }
        AuthenticateUser authenticateUser =authenticateUserService.selectAuthenticateUserByUserId(authenticateToken.getIdCard());
        String name = authenticateUser.getName();
        String id = authenticateUser.getUserId();

//        String sysId= "clt001";
        JSONObject jsonObject= new JSONObject();
        jsonObject.put("signToken",token);
        jsonObject.put("uname",name);
        jsonObject.put("uid",id);
        jsonObject.put("sysId",faceSysId);
        HttpResult ht = null;
        try {
            log.info("发送请求"+faceServerUrl+";参数"
                    +jsonObject.toJSONString());
            ht =  executePost(faceServerUrl,
                    jsonObject.toJSONString(),"UTF-8",10000);
//            ht =  executePost("https://114.115.210.223:443/EssIdentityAuthorityTest/GetAuthUrl",
//                    jsonObject.toJSONString(),"UTF-8",10000);
            log.info("GetAuthUrl结果"+ht.getContent());
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (ht==null&&ht.getStatusCode()!=200){
            return AjaxResult.error("认证服务器出错：无法链接！");
        }
        JSONObject js = JSONObject.parseObject(ht.getContent());
        if (js.containsKey("code")&&js.getInteger("code")==200){
            return AjaxResult.success("获取成功",js.getString("msg"));
        }else{
            return AjaxResult.error("认证服务器出错："+js.getString("msg"));
        }
    }
    /**
     */
    @RequestMapping(value="/getAuthUrlBackup")
    @ResponseBody
    public AjaxResult getAuthUrlBackup(@RequestBody JSONObject data) {
        String token;
        if (data.containsKey("token")) {
            token = data.getString("token");
        } else {
            return AjaxResult.error("参数类型不全");
        }
        AuthenticateToken authenticateToken = authenticateTokenService.selectAuthenticateTokenByTokenId(token);
        if (authenticateToken == null&&sign_success.equals(authenticateToken.getSignStatus())){
            return AjaxResult.error("token已失效");
        }
        if (isNull(authenticateToken.getIdCard())){
            return AjaxResult.error("token信息缺失");
        }
        AuthenticateUser authenticateUser =authenticateUserService.selectAuthenticateUserByUserId(authenticateToken.getIdCard());
        String name = authenticateUser.getName();
        String id = authenticateUser.getUserId();

//        String sysId= "clt001";
        JSONObject jsonObject= new JSONObject();
        jsonObject.put("signToken",token);
        jsonObject.put("uname",name);
        jsonObject.put("uid",id);
        jsonObject.put("sysId",faceSysId);
        jsonObject.put("partner",partner);
        HttpResult ht = null;
        try {
            log.info("发送请求"+faceServerUrl+";参数"
                    +jsonObject.toJSONString());
            ht =  executePost(faceServerUrl,
                    jsonObject.toJSONString(),"UTF-8",10000);
//            ht =  executePost("https://114.115.210.223:443/EssIdentityAuthorityTest/GetAuthUrl",
//                    jsonObject.toJSONString(),"UTF-8",10000);
            log.info("GetAuthUrl结果"+ht.getContent());
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (ht==null&&ht.getStatusCode()!=200){
            return AjaxResult.error("认证服务器出错：无法链接！");
        }
        JSONObject js = JSONObject.parseObject(ht.getContent());
        if (js.containsKey("code")&&js.getInteger("code")==200){
            return AjaxResult.success("获取成功",js.getString("msg"));
        }else{
            return AjaxResult.error("认证服务器出错："+js.getString("msg"));
        }
    }





    @RequestMapping(value="/updateAuthStatus")
    @ResponseBody
    public AjaxResult updateAuthStatus(@RequestBody JSONObject data) {
        String token;
        String authStatus;
        String errorInfo;

        if (data.containsKey("signToken")&&data.containsKey("authStatus")&&data.containsKey("errorInfo")) {
            token = data.getString("signToken");
            authStatus = data.getString("authStatus");
            errorInfo = data.getString("errorInfo");
        } else {
            return AjaxResult.error("参数类型不全");
        }
        log.info("认证状态更新"+data.toJSONString());
        AuthenticateToken authenticateToken = authenticateTokenService.selectAuthenticateTokenByTokenId(token);
        if (authenticateToken == null&&sign_success.equals(authenticateToken.getSignStatus())){
            return AjaxResult.error("token已失效");
        }
        authenticateToken.setAuthStatus(authStatus);
        authenticateToken.setAuthMsg(errorInfo);
        int result = authenticateTokenService.updateAuthenticateToken(authenticateToken);
        if (result == 1 ){
            return AjaxResult.success();
        }
        return AjaxResult.error();
    }

    @RequestMapping(value="/getTokenStatus")
    @ResponseBody
    public AjaxResult getTokenStatus(@RequestBody JSONObject data) {
        String token;
        if (data.containsKey("token")) {
            token = data.getString("token");
        } else {
            return AjaxResult.error("参数类型不全");
        }
        log.info("认证状态查询"+data.toJSONString());
        AuthenticateToken authenticateToken = authenticateTokenService.selectAuthenticateTokenByTokenId(token);
        if (authenticateToken == null){
            return AjaxResult.error("token已失效");
        }
        JSONObject js = new JSONObject();
        js.put("authStatus",authenticateToken.getAuthStatus());
        js.put("authMsg",authenticateToken.getAuthMsg());
        js.put("signStatus",authenticateToken.getSignStatus());
        return AjaxResult.success("查询成功",js);
    }

    /**
     * 根据token查询参数进行签章
     */
    @RequestMapping(value="/sign")
    @ResponseBody
    public AjaxResult sign(@RequestBody JSONObject data) throws UnsupportedEncodingException {
        String token;
        if (data.containsKey("token")) {
            token = data.getString("token");
        } else {
            return AjaxResult.error("参数类型不全");
        }
        log.info("执行签章"+data.toJSONString());
        AuthenticateToken authenticateToken = authenticateTokenService.selectAuthenticateTokenByTokenId(token);
        if (authenticateToken == null&&sign_success.equals(authenticateToken.getSignStatus())){
            return AjaxResult.error("token已失效");
        }
        String documentId = authenticateToken.getDocumentId();
        String id = authenticateToken.getIdCard();
        byte[] pdf = fileService.downloadDocument(documentId, Constants.SIGN_PDF_SUFFIX);
        if(pdf==null){
            return AjaxResult.error("文档出错了");
        }
        AuthenticateUser authenticateUser =authenticateUserService.selectAuthenticateUserByUserId(id);
        String signImg = authenticateUser.getSignImg();

        String pfx = authenticateUser.getPfx();
        String cert = authenticateUser.getCert();
        String pwd = authenticateUser.getPwd();
        String name = authenticateUser.getName();
        if(StringUtils.isEmpty(signImg)||StringUtils.isEmpty(pfx)||StringUtils.isEmpty(cert)||
                StringUtils.isEmpty(pwd)){
            return AjaxResult.error("签章资料缺失");
        }
        SealDto sealDto = new SealDto();
        sealDto.setSeal_pfx(pfx);
        sealDto.setSeal_cert(cert);
        sealDto.setSeal_pwd(pwd);
        sealDto.setSealName(name);
        sealDto.setSeal_standard("5");
        sealDto.setSeal_img(signImg);
        //签章参数
        JSONArray seals = JSONArray.parseArray(authenticateToken.getSeals());
        for (int i =0;i<seals.size();i++){
            try {
                JSONObject sealJson = seals.getJSONObject(i);
                String signType = "1";
                if (sealJson.containsKey("signType")){
                    signType = sealJson.getString("signType");
                }
                float width = 60;
                float height = 30;
                if (sealJson.containsKey("width")){
                    width = convertCoordinate(sealJson.getFloat("width"));
                }
                if (sealJson.containsKey("height")){
                    height = convertCoordinate(sealJson.getFloat("height"));
                }

                sealDto.setSeal_h((int)height);
                sealDto.setSeal_w((int)width);

                if (sealJson.containsKey("contentText")&&sealJson.containsKey("rowTextNum")&&sealJson.containsKey("font")
                        &&sealJson.containsKey("fontSize")) {
                    //审批意见 自定义图片
                    String msg = sealJson.getString("contentText");
                    String font = sealJson.getString("font");
                    int fontSize = sealJson.getInteger("fontSize");
                    int rowTextNum = sealJson.getInteger("rowTextNum");
                    //默认字体颜色黑色
                    Color color = new Color(0, 0, 0);
                    if (sealJson.containsKey("fontColor")){
                        //如果参数有设置，使用指定颜色
                        String fontColor = sealJson.getString("fontColor");
                        fontColor = fontColor.substring(1);
                        color =  new Color(Integer.parseInt(fontColor, 16)) ;
                    }
                    if (msg.length()<rowTextNum){
                        rowTextNum = msg.length();
                    }
                    ImgBean img = createTextImage(msg,font,fontSize,rowTextNum, color);
                    sealDto.setSeal_img(ESSGetBase64Encode(img.getImgData()));
                    sealDto.setSeal_w(img.getImgW()/17);
                    sealDto.setSeal_h(img.getImgH()/17);
                }
                if (sealJson.containsKey("imgW")) {
                    int imgW = sealJson.getInteger("imgW");
                    int imgH = sealJson.getInteger("imgH");
                    sealDto.setSeal_h(imgH);
                    sealDto.setSeal_w(imgW);
                }
                if (sealJson.containsKey("scale")) {
                    double scale = sealJson.getDouble("scale");
                    if (scale<0||scale>5){
                        scale=1.00;
                    }
                    sealDto.setSeal_h((int)(sealDto.getSeal_h()*scale));
                    sealDto.setSeal_w((int)(sealDto.getSeal_w()*scale));
                }

                if("1".equals(signType)){
                    PdfLocation aa = signService.findLocationByKeyword(sealJson.getString("sKeyWord"), pdf,
                            sealJson.getInteger("KeyNumber"));
                    float iOffsetX = 0;
                    float iOffsetY = 0;
                    if (sealJson.containsKey("iOffsetX")){
                        iOffsetX = convertCoordinate(sealJson.getFloat("iOffsetX"));
                    }
                    if (sealJson.containsKey("iOffsetY")){
                        iOffsetY = convertCoordinate(sealJson.getFloat("iOffsetY"));
                    }
                    if (aa == null){
                        AjaxResult.error("找不到关键字位置");
                    }else{
                        aa.setX(aa.getX()+iOffsetX);
                        aa.setY(aa.getY()+iOffsetY);
                    }
                    pdf = signService.addSeal(pdf, Base64Utils.ESSGetBase64Decode(sealDto.getSeal_img()), sealDto.getSeal_w(),
                            sealDto.getSeal_h(),
                            aa.getPageNum(), aa.getX(), aa.getY(),sealDto, IdUtils.simpleUUID(), null);
                }else if("9".equals(signType)){
                    //全局关键字文档签章
                    if (sealJson.containsKey("sKeyWord")){
                        String sKeyWord  = sealJson.getString("sKeyWord");
                        float iOffsetX = 0;
                        float iOffsetY = 0;
                        if (sealJson.containsKey("iOffsetX")){
                            iOffsetX = convertCoordinate(sealJson.getFloat("iOffsetX"));
                        }
                        if (sealJson.containsKey("iOffsetY")){
                            iOffsetY = convertCoordinate(sealJson.getFloat("iOffsetY"));
                        }
                        //关键字定位
                        List<PdfLocation> pdfLocationList =  signService.findLocationByKeywordAll(sKeyWord,pdf);

                        if (pdfLocationList==null){
                            authenticateToken.setSignStatus(sign_error);
                            authenticateTokenService.updateAuthenticateToken(authenticateToken);
                            return AjaxResult.error("关键字不存在");
                        }
                        for (PdfLocation lo :pdfLocationList) {
                            if (lo == null){
                                authenticateToken.setSignStatus(sign_error);
                                authenticateTokenService.updateAuthenticateToken(authenticateToken);
                                return AjaxResult.error("找不到关键字位置");
                            }else{
                                lo.setX(lo.getX()+iOffsetX);
                                lo.setY(lo.getY()+iOffsetY);
                            }
                            //签章
                            pdf = signService.addSeal(pdf, Base64Utils.ESSGetBase64Decode(signImg), width, height,
                                    lo.getPageNum(), lo.getX(), lo.getY(),sealDto, IdUtils.simpleUUID(), null);
                            if (pdf==null){
                                authenticateToken.setSignStatus(sign_error);
                                authenticateTokenService.updateAuthenticateToken(authenticateToken);
                                return AjaxResult.error("签章失败");
                            }
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                authenticateToken.setSignStatus(sign_error);
                authenticateTokenService.updateAuthenticateToken(authenticateToken);
                return AjaxResult.error("签章时异常");
            }
        }
        fileService.saveDocument(
                byte2Input(pdf),documentId,Constants.SIGN_PDF_SUFFIX);
        JSONObject js = new JSONObject();
        js.put("token",token);
        js.put("documentCode",documentId);
        //更新签章状态
        authenticateToken.setSignStatus(sign_success);
        authenticateTokenService.updateAuthenticateToken(authenticateToken);
        SendResult ss = producerUtil.sendMsg(smsTopicProperties.getTopic(), "thirdSignDownload",
                JSONObject.toJSONString(AjaxResult.success(new String("签章成功".getBytes(),
                        StandardCharsets.UTF_8),js)).getBytes(), null);
        return AjaxResult.success("签章成功",documentId);
    }
}
